//
//  TimerCrashVC.m
//  MRC_Playground
//
//  Created by Developer on 2022/3/31.
//

#import "TimerCrashVC.h"
#import "SimulateAdObject.h"

@interface TimerCrashVC ()<SimulateAdDelegate>

@end

@implementation TimerCrashVC{
    NSTimer *_timer;
    SimulateAdObject *_adObj;
    UIButton *_btn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    _btn = [[UIButton alloc] initWithFrame:CGRectZero];
    _btn.backgroundColor = [UIColor orangeColor];
    [_btn addTarget:self action:@selector(actionRequestAd) forControlEvents:(UIControlEventTouchUpInside)];
    [_btn setTitle:@"Request" forState:(UIControlStateNormal)];
    [self.view addSubview:_btn];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    _btn.frame = CGRectMake(10, CGRectGetMaxY(self.navigationController.navigationBar.frame) + 10, self.view.bounds.size.width - 20, 50);
}

- (void)dealloc{
    NSLog(@"timerVC dealloc");
    if (_adObj) {
        _adObj.delegate = nil;
        [_adObj release]; _adObj = nil;
    }
    [super dealloc];
}

#pragma mark - Private
- (void)actionRequestAd{
    if (!_adObj) {
        _adObj = [[SimulateAdObject alloc] init];
        _adObj.delegate = self;
    }
    [_adObj requestAd];
    
//    [self stopTimer];
    //隐性的[self retain]
    _timer = [[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(actionTimeout:) userInfo:nil repeats:NO] retain];
    NSLog(@"request timer:%@",_timer);
}

- (void)actionTimeout:(NSTimer *)timer{
    NSLog(@"timeout %@",timer);
    [self stopTimer];
    NSLog(@"%@",self);
}

- (void)stopTimer{
    if (_timer) {
        [_timer invalidate];    //隐性的[self release],如果此时self没有其他的引用，将进入dealloc，所以在stopTimer后再调用self即是对已经释放过的对象发送消息，造成崩溃
        [_timer release]; _timer = nil;
    }
}

#pragma mark - SimulateAdDelegate
- (void)sim_finishedRequest{
    NSLog(@"callback sim_finishedRequest");
    [self stopTimer];
    //此处进入 TimerCrashVC的dealloc，所以后续再调用self则会造成崩溃
//    NSLog(@"finished %@",self);
}
@end
